Page({
  data: {
    userInfo: null,
    interviewHistory: [],
    stats: {
      total: 0,
      bestScore: 0,
      avgScore: 0
    }
  },

  onLoad: function() {
    const app = getApp();
    
    // 获取用户信息
    this.setData({
      userInfo: app.globalData.userInfo,
      interviewHistory: app.globalData.interviewHistory
    });
    
    // 计算统计数据
    this.calculateStats();
  },

  onShow: function() {
    const app = getApp();
    
    // 更新面试历史
    this.setData({
      interviewHistory: app.globalData.interviewHistory
    });
    
    // 重新计算统计数据
    this.calculateStats();
  },

  // 计算统计数据
  calculateStats: function() {
    const history = this.data.interviewHistory;
    const total = history.length;
    
    let bestScore = 0;
    let totalScore = 0;
    
    history.forEach(record => {
      if (record.score > bestScore) {
        bestScore = record.score;
      }
      totalScore += record.score;
    });
    
    const avgScore = total > 0 ? Math.round(totalScore / total) : 0;
    
    this.setData({
      stats: {
        total: total,
        bestScore: bestScore,
        avgScore: avgScore
      }
    });
  },

  // 查看面试历史
  viewHistory: function() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  // 查看面试报告
  viewReport: function(e) {
    const timestamp = e.currentTarget.dataset.timestamp;
    wx.navigateTo({
      url: `/pages/report/report?timestamp=${timestamp}`
    });
  },

  // 清除历史记录
  clearHistory: function() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除所有面试历史记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          const app = getApp();
          app.globalData.interviewHistory = [];
          wx.setStorageSync('interviewHistory', []);
          
          this.setData({
            interviewHistory: [],
            stats: {
              total: 0,
              bestScore: 0,
              avgScore: 0
            }
          });
          
          wx.showToast({
            title: '已清除历史记录',
            icon: 'success'
          });
        }
      }
    });
  }
});
